package com.mattidroid.spiegel;

import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Spinner;
import android.widget.Toast;

public class MoreSettings extends Activity {
	

	GlobalClass Data;	// Define Object for access to global data
	
	// read locale settings from prefs and set accordingly
	void setLocale () {
		
		//Dynamic Override system settings LOCALE 
		//Need in all Classes
		GlobalClass GlobalData = ((GlobalClass)getApplicationContext());
	    String languageToLoad  = GlobalData.isLocaleString(GlobalData.overrideLocale);
	    GlobalClass.log(false, "MoreSettings.setLocale Locale Setting to : " + languageToLoad);
	    
	    if (languageToLoad.equals("")) {
	    	// do nothing
	    	 GlobalClass.log(false, "applicationInit.setLocale Locale EMPTY");
	    }
	    else {
	    	//Override system settings LOCALE
		    Locale locale = new Locale(languageToLoad); 
		    Locale.setDefault(locale);
		    Configuration config = new Configuration();
		    config.locale = locale;
		    getBaseContext().getResources().updateConfiguration(config, 
		    getBaseContext().getResources().getDisplayMetrics());
	    }
	    
	}
	
	void getCurrentMoreSettings(){
		
		// Point Object for access to global data to right context
	    GlobalClass Data = ((GlobalClass)getApplicationContext());
	    
		// Swipe
	    GlobalClass.log(false, "getCurrentSettings - EnableSwipeCheck :" + Data._isSwipeOn);
		CheckBox EnableSwipeCheck = (CheckBox) findViewById(R.id.EnableSwipeCheck);	
		if (Data._isSwipeOn == 1){
			EnableSwipeCheck.setChecked(true);
		}
		else {
			EnableSwipeCheck.setChecked(false);
		}
		
		// Debug 1
		CheckBox Enable_Logging_Level_1_Check = (CheckBox) findViewById(R.id.Enable_Logging_Level_1_Check);
		if (Data._isDebugLevel_1 == 1) {
			Enable_Logging_Level_1_Check.setChecked(true);
		}
		else {
			Enable_Logging_Level_1_Check.setChecked(false);
		}
		
		// Debug 2
		CheckBox Enable_Logging_Level_2_Check = (CheckBox) findViewById(R.id.Enable_Logging_Level_2_Check);
		if (Data._isDebugLevel_2 == 1) {
			Enable_Logging_Level_2_Check.setChecked(true);
		}
		else {
			Enable_Logging_Level_2_Check.setChecked(false);
		}
	
	}
	
	// Override to handle back key
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
            alertbox.setMessage(this.getString(R.string.msg_areyousure));
            alertbox.setTitle(this.getString(R.string.good_bye));
            alertbox.setPositiveButton(this.getString(R.string.yes), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
                    MoreSettings.this.finish();
                }
            });

            alertbox.setNegativeButton(this.getString(R.string.no), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
                }
            });
            alertbox.show();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }   	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.more_settings);
		GlobalClass.log(false, "EditMoreSettings ");
		
		// first get current life application settings
	    GlobalClass Data = ((GlobalClass)getApplicationContext());
	    
		Data.getStoredSettings();
		getCurrentMoreSettings();
		
	    // read locale settings from prefs and set accordingly
	    setLocale();
		
		// Locale Selection Spinnter
	    Spinner spinner = (Spinner) findViewById(R.id.Locale_Selection_Spinner);
	    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
	            this, R.array.Locale_Settings_Array, android.R.layout.simple_spinner_item);
	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    spinner.setAdapter(adapter);
	       
	    // Need to set spinner to actual stored value
	    spinner.setSelection(Data.overrideLocale);
	    GlobalClass.log(false, "MoreSettings.onCreate Spinner.setSelection: "  + Data.overrideLocale);

	    // Implement Handler for Spinner after Selection
	    spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());

		final CheckBox EnableSwipeCheck = (CheckBox) findViewById(R.id.EnableSwipeCheck);
		EnableSwipeCheck.setOnClickListener(new OnClickListener() {
			
			// first get current life application settings
		    GlobalClass Data = ((GlobalClass)getApplicationContext());
		    
			public void onClick(View v) {
				 if (EnableSwipeCheck.isChecked()) {
				 	Data._isSwipeOn = 1;
				 }
		         else {
		        	 Data._isSwipeOn = 0;
		         }
				GlobalClass.log(false,  "CheckBox setOnClickListener EnableSwipeCheck: " + Data._isSwipeOn);
			}
		});
	
		// Analyse checkboxes and watch number of tabs !!!
		final CheckBox Enable_Logging_Level_1_Check = (CheckBox) findViewById(R.id.Enable_Logging_Level_1_Check);
		Enable_Logging_Level_1_Check.setOnClickListener(new OnClickListener() {
			
			// first get current life application settings
		    GlobalClass Data = ((GlobalClass)getApplicationContext());
		    
			public void onClick(View v) {
				 if (Enable_Logging_Level_1_Check.isChecked()) {
				 	Data._isDebugLevel_1 = 1;
				 }
		         else {
		        	 Data._isDebugLevel_1 = 0;
		         }
				GlobalClass.log(false,  "CheckBox setOnClickListener Enable_Logging_Level_1_Check: " + Data._isDebugLevel_1);
			}
		});

		// Analyse checkboxes and watch number of tabs !!!
		final CheckBox Enable_Logging_Level_2_Check = (CheckBox) findViewById(R.id.Enable_Logging_Level_2_Check);
		Enable_Logging_Level_2_Check.setOnClickListener(new OnClickListener() {
			
			// first get current life application settings
		    GlobalClass Data = ((GlobalClass)getApplicationContext());
		    
			public void onClick(View v) {
				 if (Enable_Logging_Level_2_Check.isChecked()) {
				 	Data._isDebugLevel_2 = 1;
				 }
		         else {
		        	 Data._isDebugLevel_2 = 0;
		         }
				GlobalClass.log(false,  "CheckBox setOnClickListener Enable_Logging_Level_1_Check: " + Data._isDebugLevel_1);
			}
		});
								
		// Buttons from XML View
		final Button ButtonOkPressed = (Button) findViewById(R.id.ButtonOk);
		ButtonOkPressed.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// Perform action on clicks
				SaveOptions();
		    	MoreSettings.this.finish();
			}
		});
		
		final Button ButtonChancelPressed = (Button) findViewById(R.id.ButtonCancel);
		ButtonChancelPressed.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// Perform action on clicks
				CancelOptions();
			}
		});
		
    }

 // Menu Function call
    
	public void SaveOptions()
	{
		// save settings temporary
		// not needed anymore due to immediate analysis in onClickListener
		// setCurrentSettings();
	    GlobalClass Data = ((GlobalClass)getApplicationContext());
		Data.saveStoredSettings();
		
		// say something
		Toast.makeText(this,this.getString(R.string.msg_save),Toast.LENGTH_SHORT).show();
		
		// Restart Application
		GlobalClass.log(false, "EditMoreSetting.Save Options: Need to restart application");
		
		// This Restarts the Application !!!
		Intent RestartIntent = getBaseContext().getPackageManager()
        .getLaunchIntentForPackage( getBaseContext().getPackageName() );
		RestartIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(RestartIntent);
		
	}
	
	public void CancelOptions()
	{
        AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
        alertbox.setMessage(this.getString(R.string.msg_areyousure));
        alertbox.setPositiveButton(this.getString(R.string.yes), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
                MoreSettings.this.finish();
            }
        });

        alertbox.setNegativeButton(this.getString(R.string.no), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
            }
        });
        alertbox.show();
	}
    
 // Options Menu using XML File
    
    // create menu
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.settings_menu, menu);
        return true;
    }
    
    // handle return from menu selection
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.save:
            SaveOptions();
        	this.finish();
            return true;       
        case R.id.cancel:
            CancelOptions();        	
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
    public class MyOnItemSelectedListener implements OnItemSelectedListener {

        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
           // Do Something on Spinner Selected !!!
        	GlobalClass.log(true, "Spinner Selected : " + pos);
    	    // Point Object for access to global data to right context
    		GlobalClass GlobalData = ((GlobalClass)getApplicationContext());
    		// Store position globaly
    		GlobalData.overrideLocale = pos;
        }

        public void onNothingSelected(AdapterView<?> parent) {
          // Do nothing.
        }
    }
    
}